package transporter

import (
	"barge/pkg/sshx"
	"bytes"
	"io"
	"strings"
)

type RemoteExecutor struct {
	*sshx.SShClient
}

func NewRemoteExecutor(sshOpt *sshx.Option) (*RemoteExecutor, error) {
	c, err := sshx.NewSShClient(sshOpt)
	if err != nil {
		return nil, err
	}
	return &RemoteExecutor{
		SShClient: c,
	}, nil
}

func (e RemoteExecutor) Exec(cmdStmt []string, stdio, stderr io.Writer) error {
	return e.SShClient.Exec(strings.Join(cmdStmt, " "), stdio, stderr)
}

func (e RemoteExecutor) ReadFile(name string) ([]byte, error) {
	cmdStmt := []string{"cat", name}
	stdio := new(bytes.Buffer)
	stderr := new(bytes.Buffer)
	err := e.SShClient.Exec(strings.Join(cmdStmt, " "), stdio, stderr)
	if err != nil {
		return nil, err
	}
	return stdio.Bytes(), nil
}
